package net.suncaper.demo.controller;


import com.sun.org.apache.xpath.internal.SourceTree;
import net.suncaper.demo.domain.Evaluate;
import net.suncaper.demo.domain.Image;
import net.suncaper.demo.service.EvaluateService;
import net.suncaper.demo.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import net.suncaper.demo.domain.Product;
import net.suncaper.demo.service.ProductService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.github.pagehelper.PageHelper;

@Controller
@RequestMapping("/product")
public class ProductController {
    private Path newFile;
    @Autowired
    private ProductService productService;

    //private EvaluateService evaluateService;

    @Value("${upload.base-dir}")
    private String uploadBaseDir;

    @GetMapping("/add")
    public String productPage(Model model){
        model.addAttribute("product",new Product());
//        System.out.println("test");
        return "/pages/product/add-product.html";
    }

    @GetMapping("update")
    public String editPage(int id, Model model){
        model.addAttribute("product",productService.findProductById(id));
        return "/pages/product/edit-product.html";
    }
    @PostMapping("/update")
    public String updateProduct(Product product){
        int id = product.getStoreId();
        productService.updateProduct(product);
        return "redirect:/product/store/allproductbySid?storeId="+id;
    }


    @PostMapping("/add")
//    public String saveProduct(Product product){
//        productService.saveProduct(product);
//        return "redirect:/product";
//    }
    public String saveProduct(Product product,@RequestParam("file") MultipartFile[] file ) throws IOException {

        productService.saveProduct(product);

        newFile = FileSystems.getDefault().getPath(uploadBaseDir,String.valueOf(product.getProductId()));
        if (Files.notExists(newFile)){
            Files.createDirectories(newFile);
        }
        productService.savePath(product,newFile);
//        if (file != null && file.getBytes().length > 0) {
//            Files.write(Paths.get(uploadBaseDir, String.valueOf(product.getProductId()), file.getOriginalFilename()), file.getBytes());
//        }
        int id=product.getProductId();
        int storeId=product.getStoreId();
        if(file != null && file.length != 0){
            if(null != file && file.length > 0){
                //遍历并保存文件
                for(MultipartFile f : file){
                    Files.write(Paths.get(uploadBaseDir, String.valueOf(product.getProductId()), f.getOriginalFilename()), f.getBytes());
                    Image image=new Image();
                    String type=f.getContentType();
                    String name = f.getOriginalFilename();
                    image.setFilename(name);
                    image.setProductId(id);
                    image.setType(type);
                    productService.addImage(image);
                }

            }
        }
        String path = file[0].getOriginalFilename();
        productService.setMainImage(product,path);
        productService.setPicnum(product);
        return "redirect:/product/store/allproductbySid?storeId="+storeId;
    }
//    public String saveProduct(Product product){
//        productService.saveProduct(product);
//        return "redirect:/product/show";
//    }

    @GetMapping("delete")
    public String deletePage(int id, Model model){
        model.addAttribute("product",productService.findProductById(id));
        return "/pages/product/del-product.html";
    }

    @PostMapping("/delete")
    public String deleteProductById(Product product){
//        Product product=productService.findProductById(id);
        int storeId=product.getStoreId();
        int id=product.getProductId();
        productService.deleteProduct(id);
        return "redirect:/product/store/allproductbySid?storeId="+storeId;
    }

    @GetMapping("/{productId}")
    public String deleteProduct(@PathVariable("productId") String id){
        return "redirect:/product/show";
    }

    @RequestMapping("/search")
    @ResponseBody
    public List<Product> findProducts(){
        return productService.findProduct();
    }

    @RequestMapping("/show")

    public String ProductPage(Model model,@RequestParam(value = "productName",required = false) String name){
        List<Product>products=productService.findProduct();
        model.addAttribute("products",products);
        return "pages/product/list.html";
    }

    @GetMapping("/searchbyType")
    public String searchProductsByType(String type,Model model){
        List<Product>products=productService.findProductByType(type);
        model.addAttribute("products",products);
//        return "redirect:../public/home/home.html";
        return "pages/product/search.html";
    }

    @GetMapping("/searchbyAll")
    public String searchProductsAll(String s,Model model){
        List<Product>products=productService.searchProduct(s);
        List<Product>products1=productService.findProductByType(s);
        Set set = new HashSet();
        set.addAll(products);
        set.addAll(products1);
        System.out.println(set);
        model.addAttribute("products",set);
        return "/pages/home/search.html";
    }

    //显示对应storeId的所有商品
    @GetMapping("/store/allproductbySid")
    public String productfromstorePage(Model model,int storeId){
        int storeID = Integer.valueOf(storeId).intValue();
        List<Product> products = productService.findProductBystoreId(storeID);
        model.addAttribute("products",products);
        return "/pages/store/allproductbySid";
    }

    @GetMapping("/searchbyId")
    public String searchProductsAbyId(int id,Model model1,Model model2,Model model3){
        Product products=productService.searchProduct(id);
        int productId=products.getProductId();
        List<Evaluate> evaluates = productService.getEvaluatebyId(productId);
        String path=products.getProductPics();
        List<Image> images = productService.getImages(productId);
//        File file = new File(path);
//        File[] f=file.listFiles();
//        int num=file.listFiles().length;
//        List<String> p = new ArrayList<String>(); ;
//        for (int i=0;i<num;i++){
//            p.set(i, f[i].getPath());
//        }
//        System.out.println(f[0].getPath());
        model1.addAttribute("products",products);
        model2.addAttribute("evaluates",evaluates);
        model3.addAttribute("images",images);
        return "/pages/home/introduction.html";
    }

    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity<Resource> download(@RequestParam("fileName") String fileName,@RequestParam("productId") String productId) throws IOException {
        Path path = Paths.get(uploadBaseDir,productId, fileName);
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

        return ResponseEntity.ok()
//                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("image/jpeg"))
                .body(resource);
    }


//
//    @RequestMapping("admin_product_list")
//    public String list(int cid, Model model, Page page) {
//        Locale.Category c = categoryService.get(cid);
//
//        PageHelper.offsetPage(page.getStart(),page.getCount());
//        List<Product> ps = productService.list(cid);
//
//        int total = (int) new PageInfo<>(ps).getTotal();
//        page.setTotal(total);
//        page.setParam("&cid="+c.getId());
//
//        model.addAttribute("ps", ps);
//        model.addAttribute("c", c);
//        model.addAttribute("page", page);
//
//        return "admin/listProduct";
//    }



}
